import logging
log = logging.getLogger('anims')
log.debug("imported")

from pyknic.resources.tiledtmxloader import ImageLoaderPyglet

import pyglet

from constants import *

def MakeAnimFromFrames(frame_names, timeperframe = 0.1, loop = True):
       frames = []
       for filename in frame_names:
           frames.append(pyglet.image.load(DATA_DIR+"/"+filename))
           
       anim = pyglet.image.Animation.from_image_sequence(frames, timeperframe)
       return anim
    
def GetAnimFrames(image, sx, sy):
    log.info("GetAnimFrames" +str((image, sx, sy)))

    anim_images = OpenFile( image, [sx,sy])

    log.debug( "Got frames:"+str(len(anim_images)))
    return anim_images

_anims = {}        
def GetAnimSeqFromFile(name, dim, timeperframe = 0.1, loop = True):
        seq = GetAnimFrames(name, dim[0], dim[1])
        res = pyglet.image.Animation.from_image_sequence(seq,  period = timeperframe, loop = loop)
        return res
    
_frames = {}  
# TODO: cache frames      
def GetFramesFromFile(name, dim):
        seq = GetAnimFrames(name, dim[0], dim[1])
        res = []
        for img in seq:
            res.append(pyglet.image.Animation.from_image_sequence([img],  period = 0.1, loop = True))
        return res
    
_opened_files = {}        
def OpenFile(filename, std_dim):
    images = _opened_files.get(filename+str(std_dim))
    if images is None:
        ildr = ImageLoaderPyglet()
        tile_width, tile_height  = std_dim
        images = ildr.load_image_parts( DATA_DIR+"/"+filename, 0, 0, tile_width, tile_height)
        _opened_files[filename+str(std_dim)] = images
    else:
        log.info("OpenFile ["+filename+"] cached")
        
    return images
